package com.projectpractice.service;


import com.projectpractice.bean.User;
import com.projectpractice.common.utils.Md5Util;
import com.projectpractice.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

//@Service 注解 ：UserServiceImpl如果打上@Service，
// 在Spring启动的时候，会被扫描到Spring容器中，组件被Spring容器所管理。
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public User regist(User user) {
        if(userRepository.getUserByName(user.getName())!=null){
            return null;//用户已存在返回0
        }else {
            //对密码MD5加密 salt为用户名
            String encryptedPassword = Md5Util.encrypt(user.getName(), user.getPassword());
            user.setPassword(encryptedPassword);
            userRepository.saveAndFlush(user);
            return user;//添加用户到数据库，注册成功，返回1
        }
    }

//    @Override
//    public User login(User user) {
//        Optional<User> userOptional = Optional.ofNullable(userRepository.getUserByName(user.getName()));
//        if(userOptional.isPresent()&&userOptional.get().getPassword().equals(user.getPassword())){
//            return user;
//        }
//        else{
//            return null;
//        }
//    }

    @Override
    public User forget(User user) {
        Optional<User> userOptional = Optional.ofNullable(userRepository.getUserByName(user.getName()));
        if(userOptional.isPresent()&&userOptional.get().getEmail().equals(user.getEmail())){
            return userOptional.get();
        }
        else{
            return null;
        }
    }

    @Override
    public List<User> list() {
        return userRepository.findAll();
    }

    @Override
    public int delete(Integer id) {
        try{
            userRepository.deleteById(id);
        } catch (Exception e) {
            return 0;
        }
        return 1;
    }

    @Override
    public User getUserById(Integer id) {
        return userRepository.getUserById(id);
    }

    @Override
    public int update(User u) {
        String encryptedPassword = Md5Util.encrypt(u.getName(), u.getPassword());
        u.setPassword(encryptedPassword);
        userRepository.updateById(u.getId(),u.getName(),u.getHeadpic(),u.getPassword(),u.getSex(),u.getEmail(),u.getRole());
        return 1;
    }

    @Override
    public User getUserByName(String name) {
        return userRepository.getUserByName(name);
    }
}

